package com.huidu.bitrade.consumer;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.huidu.bitrade.config.MQTraceAspect;
import com.huidu.bitrade.constant.ActivityRewardType;
import com.huidu.bitrade.constant.RewardRecordType;
import com.huidu.bitrade.constant.TransactionType;
import com.huidu.bitrade.entity.*;
import com.huidu.bitrade.service.*;
import com.huidu.bitrade.util.BigDecimalUtils;
import com.spark.bipay.constant.CoinType;
import com.spark.bipay.entity.Address;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;

@Slf4j
@Component
@AllArgsConstructor
public class MemberConsumer {

    private final CoinService coinService;
    private final MemberWalletService memberWalletService;
    private final RewardActivitySettingService rewardActivitySettingService;
    private final MemberService memberService;
    private final RewardRecordService rewardRecordService;
    private final MemberTransactionService memberTransactionService;
    private final BiPayService biPayService;

//    /**
//     * 重置用户钱包地址
//     * @param data
//     */
//    @Trace(operationName = "consumerTag-MemberConsumer-resetAddress")
//    @KafkaListener(topics = {"reset-member-address"})
//    public void resetAddress(List<ConsumerRecord<String, String>> data) {
//        Iterator<ConsumerRecord<String, String>> iterator = data.iterator();
//        MQTraceAspect.consumerData("reset-member-address",data,"重置用户钱包地址");
//        while (iterator.hasNext()){
//            ConsumerRecord<String, String> record = iterator.next();
//            String content = record.value();
//            JSONObject json = JSON.parseObject(content);
//            Coin coin = coinService.findByUnit(record.key());
////            log.info("充值用户钱包获取到消息：{},content:{},json:{},coin:{}",record,content,json,coin);
//            Assert.notNull(coin, "coin null");
//            Long memberId = json.getLong("uid");
//
//            MemberWallet memberWallet = memberWalletService.findByCoinUnitAndMemberId(record.key(), json.getLong("uid"));
//            Assert.notNull(memberWallet, "wallet null");
//            String coinType = "";
//            switch (coin.getUnit()) {
//                case "BTC":
//                    coinType = CoinType.Bitcoin.getCode();
//                    break;
//                case "ETH":
//                case "USDT":
//                case "EUSDT":
//                case "USDT-ERC20":
//                case "AAVE":
//                case "LINK":
//                case "SHIB":
//                case "UNI":
//                case "BAL":
//                case "CHZ":
//                case "CRV":
//                case "GLM":
//                    coinType = CoinType.Ethereum.getCode();
//                    break;
//                case "TRX":
//                case "USDT-TRC20":
//                case "TUSDT":
//                case "TRCUSDT":
//                case "HDZ":
//                    coinType = CoinType.TRX.getCode();
//                    break;
//                case "LTC":
//                    coinType = CoinType.Litecoin.getCode();
//                    break;
//                case "DOGE":
//                    coinType = CoinType.Dogecoin.getCode();
//                    break;
//                case "ETC":
//                    coinType = CoinType.EthereumClassic.getCode();
//                    break;
//                case "XRP":
//                    coinType = CoinType.Ripple.getCode();
//                    break;
//                case "BCH":
//                    coinType = CoinType.Bitcoincash.getCode();
//                    break;
//                case "EOS":
//                    coinType = CoinType.EOS.getCode();
//                    break;
//                case "ZEC":
//                    coinType = CoinType.ZEC.getCode();
//                    break;
//                case "STO":
//                    coinType = CoinType.STO.getCode();
//                    break;
//                case "TEC":
//                    coinType = CoinType.TEC.getCode();
//                    break;
//                case "NEO":
//                    coinType = CoinType.NEO.getCode();
//                    break;
//                case "TECO":
//                    coinType = CoinType.TECO.getCode();
//                    break;
//                case "HDC":
//                    coinType = CoinType.HDC.getCode();
//                    break;
//                case "FIL":
//                    coinType = CoinType.FIL.getCode();
//                    break;
//                case "CNHD":
//                    coinType = CoinType.CNHD.getCode();
//                    break;
//                case "ZYDC":
//                    coinType = CoinType.ZYDC.getCode();
//                    break;
//                case "DSH":
//                    coinType = CoinType.DSH.getCode();
//                    break;
//                case "ALEOTZ":
//                    coinType = CoinType.ALEOTZ.getCode();
//                    break;
////            case "HECO":
////            case "HECODOT":
////                coinType = CoinType.HECO.getCode();
////                break;
//            }
//            if (coinType.equals("")) {
//                log.error("unknown coin type");
//                return;
//            }
//            Address addressBack = biPayService.createCoinAddress(coinType, String.valueOf(memberId));
//            if (addressBack != null) {
//                String address = addressBack.getAddress();
//                memberWallet.setAddress(address);
//                memberWalletService.save(memberWallet);
//            }
//        }
//    }

    /**
     * 重置用户钱包地址
     * @param data
     */
    @Trace(operationName = "consumerTag-MemberConsumer-resetAddress")
    @KafkaListener(topics = {"reset-member-address"})
    public void resetAddress(List<ConsumerRecord<String, String>> data) {
        Iterator<ConsumerRecord<String, String>> iterator = data.iterator();
        MQTraceAspect.consumerData("reset-member-address",data,"重置用户钱包地址");
        while (iterator.hasNext()){
            ConsumerRecord<String, String> record = iterator.next();
            String content = record.value();
            JSONObject json = JSON.parseObject(content);
            log.info("收到充值用户地址消息：{}",json);
            Coin coin = coinService.findByUnit(record.key());
            Assert.notNull(coin, "coin null");
            Long memberId = json.getLong("uid");

            MemberWallet memberWallet = memberWalletService.findByCoinUnitAndMemberId(record.key(), json.getLong("uid"));
            Assert.notNull(memberWallet, "wallet null");
            String coinType = "";
            switch (coin.getUnit()) {
                case "HDZ":
                    coinType = CoinType.TRX.getNet();
                    break;
                case "HDC":
                    coinType = CoinType.HDC.getNet();
                    break;
                case "CNHD":
                    coinType = CoinType.CNHD.getNet();
                    break;
                case "ZYDC":
                    coinType = CoinType.ZYDC.getNet();
                    break;
                case "DSH":
                    coinType = CoinType.DSH.getNet();
                    break;
                case "ALEOTZ":
                    coinType = CoinType.ALEOTZ.getNet();
                    break;
            }
            if (coinType.equals("")) {
                log.error("unknown coin type");
                return;
            }
            String address = biPayService.createCoinAddressByHdWallet(coinType, String.valueOf(memberId));
            if (address != null) {
                memberWallet.setAddress(address);
                memberWalletService.save(memberWallet);
            }
        }
    }


    /**
     * 客户注册消息
     * @param content
     */
    @Trace(operationName = "consumerTag-MemberConsumer-handle")
    @KafkaListener(topics = {"member-register"})
    public void handle(String content) {
        log.info("handle member-register,data={}", content);
        MQTraceAspect.consumerData("member-register",content,"客户注册消息");
        if (StringUtils.isEmpty(content)) {
            return;
        }
        JSONObject json = JSON.parseObject(content);
        if(json == null) {
            return ;
        }
        //获取所有支持的币种
        List<Coin> coins = coinService.findAll();
        for (Coin coin : coins) {
            MemberWallet wallet = new MemberWallet();
            wallet.setCoin(coin);
            wallet.setMemberId(json.getLong("uid"));
            wallet.setBalance(new BigDecimal(0));
            wallet.setFrozenBalance(new BigDecimal(0));
            wallet.setSystemFrozen(new BigDecimal(0));
            wallet.setAddress("");
            memberWalletService.save(wallet);
        }
        //注册活动奖励
        RewardActivitySetting rewardActivitySetting = rewardActivitySettingService.findByType(ActivityRewardType.REGISTER);
        if (rewardActivitySetting == null) {
            return;
        }
        MemberWallet memberWallet = memberWalletService.findByCoinAndMemberId(rewardActivitySetting.getCoin(), json.getLong("uid"));
        if (memberWallet == null) {
            return;
        }
        // 奖励币
        BigDecimal amount3=JSONObject.parseObject(rewardActivitySetting.getInfo()).getBigDecimal("amount");
        memberWallet.setBalance(BigDecimalUtils.add(memberWallet.getBalance(),amount3));
        memberWalletService.save(memberWallet);
        // 保存奖励记录
        Member member = memberService.findOne(json.getLong("uid"));
        RewardRecord rewardRecord3 = new RewardRecord();
        rewardRecord3.setAmount(amount3);
        rewardRecord3.setCoin(rewardActivitySetting.getCoin());
        rewardRecord3.setMember(member);
        rewardRecord3.setRemark(rewardActivitySetting.getType().getCnName());
        rewardRecord3.setType(RewardRecordType.ACTIVITY);
        rewardRecordService.save(rewardRecord3);
        // 保存资产变更记录
        MemberTransaction memberTransaction = new MemberTransaction();
        memberTransaction.setFee(BigDecimal.ZERO);
        memberTransaction.setAmount(amount3);
        memberTransaction.setSymbol(rewardActivitySetting.getCoin().getUnit());
        memberTransaction.setType(TransactionType.ACTIVITY_AWARD);
        memberTransaction.setMemberId(member.getId());
        memberTransaction.setDiscountFee("0");
        memberTransaction.setRealFee("0");
        memberTransactionService.save(memberTransaction);
    }
}
